<template>
  <div class="app-container">
    <el-row>
      <!-- <el-col :span="18">
        <div id="Boer" style="width: 1200px; height: 300px"></div>
      </el-col>

      <el-form
        ref="requestForm"
        :inline="false"
        class=""
        :model="requestForm"
        label-width="120px"
      >
        <el-col class="search-conditions" :span="6">
          <el-form-item label="起始频率:" prop="startUnit">
            <el-input
              v-model="formItem.startUnit"
              type="text"
              placeholder=""
              style="width: 220px"
            >
              <i slot="suffix" style="font-style: normal; margin-right: 10px">
                /{{ freqUnit }}
              </i>
            </el-input>
          </el-form-item>

          <el-form-item label="终止频率:" prop="endUnit">
            <el-input
              v-model="formItem.endUnit"
              type="text"
              placeholder=""
              style="width: 220px"
            >
              <i slot="suffix" style="font-style: normal; margin-right: 10px">
                /{{ freqUnit }}
              </i>
            </el-input>
          </el-form-item>

          <el-form-item label="步进:" prop="step">
            <el-select v-model="formItem.step" style="width: 220px">
              <el-option
                v-for="item in stepList"
                :key="item.id"
                :label="item.val"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :disabled="boerStartDis" @click="start">
              启动
            </el-button>
            <el-button type="danger" :disabled="boerTerminateDis" @click="stop">
              停止
            </el-button>
          </el-form-item>
        </el-col>
      </el-form> -->
      <el-col :span="18">
        <div id="Boer" style="width: 100%; height: 300px"></div>
      </el-col>

      <el-form
        ref="requestForm"
        :inline="false"
        class="right-condition"
        :model="requestForm"
        label-width="120px"
      >
        <el-col :span="6">
          <span class="requestFormTitle">波尔平台</span>
          <el-form-item label="请选择设备:" prop="selected">
            <el-select
              v-model="requestForm.selected"
              style="width: 220px"
              @change="getTraceDataBoer()"
            >
              <el-option
                v-for="item in listDevicesBoer"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-row class="roleInputRow">
      <el-col :span="18">
        <div id="Deli" style="width: 100%; height: 300px"></div>
      </el-col>

      <el-form
        ref="requestFormDeli"
        :inline="false"
        class="right-condition"
        :model="requestFormDeli"
        label-width="120px"
      >
        <el-col :span="6">
          <span class="requestFormTitle">德力平台</span>
          <el-form-item label="请选择设备:">
            <el-select
              v-model="requestFormDeli.selected"
              style="width: 220px"
              @change="getTraceDataDeli($event)"
            >
              <el-option
                v-for="item in listDevicesDeli"
                :key="item.id"
                :label="item.imei + item.create_dt"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-row class="roleInputRow">
      <el-col :span="18">
        <div id="Josh" style="width: 100%; height: 300px"></div>
      </el-col>

      <el-form
        ref="requestFormJosh"
        :inline="false"
        class="right-condition"
        :model="requestFormJosh"
        label-width="120px"
      >
        <el-col :span="6">
          <span class="requestFormTitle">卓晟平台</span>
          <el-form-item label="请选择设备:">
            <el-select
              v-model="requestFormJosh.selected"
              style="width: 220px"
              @change="getTraceDataJosh($event)"
            >
              <el-option
                v-for="item in listDevicesJosh"
                :key="item.id"
                :label="item.imei + item.create_dt"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-row>
      <el-col :span="18">
        <div id="nate-data-spec" style="width: 100%; height: 300px"></div>
      </el-col>

      <el-form
        ref="requestFormNate"
        :inline="false"
        class="right-condition"
        :model="requestFormNate"
        label-width="120px"
      >
        <el-col :span="6">
          <span class="requestFormTitle">纳特平台</span>
          <el-form-item label="请选择设备:">
            <el-select
              v-model="requestFormNate.mfid"
              style="width: 220px"
              @change="refreshNateChart($event)"
            >
              <el-option
                v-for="item in boxInfos"
                :key="item.equid"
                :label="item.mfid"
                :value="item.mfid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios'
// import * as Echarts from 'echarts/lib/echarts'
let ws = null
let heartHandler = null
let myChart = null
export default {
  name: 'CombineThree',
  data: () => {
    return {
      boerStartDis: false,
      boerTerminateDis: true,
      requestForm: {
        selected: '无'
      },
      requestFormNate: {
        startUnit: '',
        endUnit: '',
        step: '',
        mfid: 0
      },
      requestFormDeli: {
        startUnit: '',
        endUnit: '',
        step: '',
        selected: ''
      },
      requestFormJosh: {
        startUnit: '',
        endUnit: '',
        step: '',
        selected: ''
      },
      selected: '',
      list: [],
      listDevicesDeli: [],
      listDevicesJosh: [],
      listDevicesBoer: [{ id: '无', name: '无' }, { id: '22010001110001', name: '设备22010001110001' }],
      formItem: {
        startUnit: '',
        endUnit: '',
        step: '',
      },
      stepList: [
        {
          id: 25,
          val: '25kHz',
        },
        {
          id: 50,
          val: '50kHz',
        },
        {
          id: 100,
          val: '100kHz',
        },
      ],
      mfid: 0,//纳特3个设备选中的mfid
      boxInfos: [],
      freqUnit: 'Mhz',
      orgOptions: {},
    }
  },
  mounted () {
    // myChart = this.$echarts.init(document.getElementById('Boer'))
    this.deliDevices()
    this.joshDevices()
    // this.getTraceDataBoer()
    // this.getTraceDataNate()
    this.nateDevices()
    // this.start()
  },
  methods: {
    nateDevices () {
      axios.get('http://47.118.20.181:8080/box').then(response => {
        if (Object.keys(response.data).length != 0) {
          console.log('nate盒子设备的信息 -> ', JSON.stringify(response.data))
          this.boxInfos = response.data
          let emptyObject = {}
          emptyObject.mfid = '无';
          this.boxInfos.unshift(emptyObject)
          this.requestFormNate.mfid = '无'
          // this.requestFormNate.mfid = this.boxInfos[0].mfid
          this.mfid = this.requestFormNate.mfid
          // let notifyMsg = '当前设备站点id是:' + this.formItem.mfid
          // this.$baseNotify(notifyMsg, '提示', 'success', 'bottom-right')
          // this.init()
        }
      })
    },
    deliDevices () {
      axios.get('http://47.118.20.181:8080/deli/devices').then(
        function (response) {
          this.listDevicesDeli = response.data.data
          let emptyObject = {}
          emptyObject.id = 0
          emptyObject.imei = '无'
          emptyObject.create_dt = ''
          this.listDevicesDeli.unshift(emptyObject)
          this.requestFormDeli.selected = 0
          // this.requestFormDeli.selected = this.listDevicesDeli[0].id
          //this.getTraceDataDeli(this.requestFormDeli.selected)
        }.bind(this)
      )
    },
    joshDevices () {
      const baseUrl = 'http://47.118.20.181:8080'
      axios.get(`${baseUrl}/josh/devices`).then(
        function (response) {
          this.listDevicesJosh = response.data.data
          let emptyObj = {}
          emptyObj.id = 0
          emptyObj.imei = '无'
          emptyObj.create_dt = ''
          this.listDevicesJosh.unshift(emptyObj)
          this.requestFormJosh.selected = 0
          //this.requestFormJosh.selected = this.listDevicesJosh[0].id
          //this.getTraceDataJosh(this.requestFormJosh.selected)
        }.bind(this)
      )
    },
    getTraceDataDeli (deviceId) {
      let dom = document.getElementById('Deli')
      let myChart = this.$echarts.init(dom)
      myChart.showLoading({
        text: '加载中...请稍后',
        color: '#47B485',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        zlevel: 0
      })
      axios
        .get('http://47.118.20.181:8080/deli/records?device_id=' + deviceId)
        .then(response => {
          //console.log(JSON.stringify(response.data.data))
          if (response.data.status == 'success') {
            if (response.data.data.length == 0) {
              const dom = document.getElementById('Deli')
              dom.innerHTML = '该设备暂无数据'
              dom.removeAttribute('_echarts_instance_')
              return
            }
            let [x, y, remarks] = onRecordsDeli(response.data.data[0])
            // eslint-disable-next-line no-unused-vars
            let { frequency, span, unit, ref, mr } = remarks
            this.orgOptions = {
              title: {
                text: '德力场强仪',
                left: 'center',
              },
              // backgroundColor: 'black',
              // darkMode: true,
              tooltip: {
                trigger: 'axis',
              },
              legend: {
                show: true,
                data: ['场强'],
                left: 'left',
                formatter: function (name) {
                  return name + '(' + unit + ')'
                },
              },
              xAxis: {
                data: x,
                axisLabel: {
                  // eslint-disable-next-line no-unused-vars
                  formatter: function (value, index) {
                    return value + 'MHz'
                  },
                },
              },
              yAxis: {
                type: 'value',
              },
              series: [
                {
                  name: '场强',
                  type: 'line',
                  data: y,
                },
              ],
              dataZoom: [
                {   // 这个dataZoom组件，默认控制x轴。
                  type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                  start: 0,      // 左边在 10% 的位置。
                  end: 100         // 右边在 60% 的位置。
                }
              ],
            }
            myChart.hideLoading()
            myChart.setOption(this.orgOptions)
          } else {
            console.log(`get data for ${deviceId} failed`)
          }
        }
        )
    },
    getTraceDataJosh (deviceId) {
      const dom = document.getElementById('Josh')
      let myChart = this.$echarts.init(dom)
      myChart.showLoading({
        text: '加载中...请稍后',
        color: '#47B485',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        zlevel: 0
      })
      const baseUrl = 'http://47.118.20.181:8080'
      axios.get(`${baseUrl}/josh/records?device_id=` + deviceId).then(response => {
        // console.log(JSON.stringify(response))
        if (response.data.status == 'success') {
          let [x, y, remarks] = onRecordsJosh(response.data.data[0])
          let { frequency, span, unit, ref, mr } = remarks
          this.orgOptions = {
            title: {
              text: '卓晟虚拟接收机',
              left: 'center',
            },
            // backgroundColor: 'black',
            // darkMode: true,
            tooltip: {
              trigger: 'axis',
            },
            legend: {
              show: true,
              data: ['场强'],
              left: 'left',
              formatter: function (name) {
                return name + '(' + unit + ')'
              },
            },
            xAxis: {
              data: x,
              axisLabel: {
                formatter: function (value, index) {
                  return value + 'MHz'
                },
              },
            },
            yAxis: {
              type: 'value',
            },
            series: [
              {
                name: '场强',
                type: 'line',
                data: y,
              },
            ],
            dataZoom: [
              {   // 这个dataZoom组件，默认控制x轴。
                type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                start: 0,      // 左边在 10% 的位置。
                end: 100         // 右边在 60% 的位置。
              }
            ],
          }

          myChart.hideLoading()
          myChart.setOption(this.orgOptions)

          let scatterData = []
          for (let index in x) {
            // console.log(index)
            let item = []
            item.push(x[index])
            item.push(y[index])
            scatterData.push(item)
          }

          let maxVal = Math.max.apply(null, y)
          let minVal = Math.min.apply(null, y)

          this.scatterOptions = {
            title: {
              text: '',
              left: 'center',
              top: 0,
            },
            visualMap: {
              min: minVal,
              max: maxVal,
              dimension: 1,
              orient: 'vertical',
              right: 10,
              top: 'center',
              text: ['强', '弱'],
              calculable: true,
              inRange: {
                color: ['#f2c31a', '#24b7f2'],
              },
            },
            tooltip: {
              trigger: 'item',
              axisPointer: {
                type: 'cross',
              },
            },
            xAxis: [
              {
                type: 'value',
                axisLabel: {
                  formatter: function (value, index) {
                    return value + 'MHz'
                  },
                },
              },
            ],
            yAxis: [
              {
                type: 'value',
              },
            ],
            series: [
              {
                name: '场强',
                type: 'scatter',
                symbolSize: 5,
                // itemStyle: {
                //     normal: {
                //         borderWidth: 0.2,
                //         borderColor: '#fff'
                //     }
                // },
                data: scatterData,
              },
            ],
          }
          // let scatterChart = this.$echarts.init(
          //   document.getElementById('scatter')
          // )
          // scatterChart.setOption(this.scatterOptions)
        } else {
          console.log(`get data for ${deviceId} failed`)
        }
      }
      )
    },
    getTraceDataBoer () {
      let dom = document.getElementById('Boer')
      let myChart = this.$echarts.init(dom)
      myChart.showLoading({
        text: '加载中...请稍后',
        color: '#47B485',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        zlevel: 0
      })
      axios
        .get('http://47.118.20.181:8080/boer/records')
        .then(response => {
          if (response.data.data.length == 0) {
            const dom = document.getElementById('Boer')
            dom.innerHTML = '该设备暂无数据'
            dom.removeAttribute('_echarts_instance_')
            return
          }
          let [x, max, avg, noiseAvg] = onRecordsBoer(response.data)
          // eslint-disable-next-line no-unused-vars
          this.orgOptions = {
            title: {
              text: '波尔平台调用',
              left: 'center',
            },
            // backgroundColor: 'black',
            // darkMode: true,
            tooltip: {
              trigger: 'axis',
            },
            legend: {
              show: true,
              data: ['平均值'],
              left: 'left',
              formatter: function (name) {
                return name + '(' + 'dbuv' + ')'
              },
            },
            xAxis: {
              data: x,
              axisLabel: {
                // eslint-disable-next-line no-unused-vars
                formatter: function (value, index) {
                  return value + 'MHz'
                },
              },
            },
            yAxis: {
              type: 'value',
            },
            series: [
              // {
              //   name: '最大值',
              //   type: 'line',
              //   data: max,
              // },
              {
                name: '平均值',
                type: 'line',
                data: avg,
              }
              // {
              //   name: '噪音',
              //   type: 'line',
              //   data: noiseAvg,
              // }
            ],
            dataZoom: [
              {   // 这个dataZoom组件，默认控制x轴。
                type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                start: 0,      // 左边在 10% 的位置。
                end: 100         // 右边在 60% 的位置。
              }
            ],
          }
          myChart.hideLoading()
          myChart.setOption(this.orgOptions)
        }
        )
    },
    refreshNateChart () {
      this.getTraceDataNate(this.requestFormNate.mfid)
    },
    getTraceDataNate (mfid) {
      let myChart = this.$echarts.init(document.getElementById('nate-data-spec'))
      myChart.showLoading({
        text: '加载中...请稍后',
        color: '#47B485',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        zlevel: 0
      })
      const baseUrl = 'http://47.118.20.181:8080'
      // const baseUrl = 'http://47.118.20.181:8080'
      axios.get(`${baseUrl}/data/spec?mfid=` + mfid).then(
        response => {
          if (response.data.length > 0) {
            let [x, y] = onSpecRecords(response.data[0])
            this.orgOptions = {
              title: {
                text: '纳特平台调用',
                left: 'center',
              },
              // backgroundColor: 'black',
              // darkMode: true,
              tooltip: {
                trigger: 'axis',
              },
              legend: {
                show: true,
                data: ['强度'],
                left: 'left',
                formatter: function (name) {
                  return name + '(' + 'dbuv' + ')'
                },
              },
              xAxis: {
                data: x,
                axisLabel: {
                  formatter: function (value, index) {
                    return value + 'MHz'
                  },
                },
              },
              yAxis: {
                type: 'value',
              },
              series: [
                {
                  name: '强度',
                  type: 'line',
                  data: y,
                },
              ],
              dataZoom: [
                {   // 这个dataZoom组件，默认控制x轴。
                  type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                  start: 0,      // 左边在 10% 的位置。
                  end: 100         // 右边在 60% 的位置。
                }
              ],
            }
            myChart.hideLoading()
            myChart.setOption(this.orgOptions)
          } else {
            const dom = document.getElementById('nate-data-spec')
            dom.innerHTML = '该设备暂无数据'
            dom.removeAttribute('_echarts_instance_')
          }
        })
    },
    start () {
      console.log('开始连接Ws')
      this.boerStartDis = true
      this.boerTerminateDis = false
      // ws = new WebSocket("ws://127.0.0.1:6003/ws");
      ws = new WebSocket('ws://47.118.20.181:6003/ws') //公网

      // eslint-disable-next-line no-unused-vars
      ws.onopen = function (evt) {
        console.log('Connection opened')
        heartHandler = setInterval(() => {
          ws.send('keepalive')
        }, 3000)
        let obj = {
          cmd: 'start',
          type: 'B_PScan',
          startfreq: 925000000,
          stopfreq: 960000000,
          step: 100000,
        }
        let cmd = JSON.stringify(obj)
        ws.send(cmd)
      }.bind(this)

      ws.onmessage = function (evt) {
        // console.log('收到消息')
        let traceData = evt.data
        // console.log(traceData)
        // this.onTraceData(traceData);
        let [x, y] = onRecords(traceData)
        // eslint-disable-next-line no-unused-vars
        let unit = 'dbuv'
        let orgOptions = {
          title: {
            text: '波尔管控中心调用',
            left: 'center',
          },
          // backgroundColor: 'black',
          // darkMode: true,
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            show: true,
            data: ['强度'],
            left: 'left',
            formatter: function (name) {
              return name + '(' + unit + ')'
            },
          },
          xAxis: {
            data: x,
            axisLabel: {
              // eslint-disable-next-line no-unused-vars
              formatter: function (value, index) {
                return value + 'MHz'
              },
            },
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '强度',
              type: 'line',
              data: y,
            },
          ],
        }
        myChart.setOption(orgOptions)
      }

      // eslint-disable-next-line no-unused-vars
      ws.onclose = function (evt) {
        console.log('Connection closed.')
      }
    },
    stop () {
      this.boerStartDis = false
      this.boerTerminateDis = true
      let obj = { cmd: 'stop' }
      let cmd = JSON.stringify(obj)
      ws.send(cmd)
      if (heartHandler) {
        clearInterval(heartHandler)
        heartHandler = null
      }
      if (ws) {
        ws.close()
        ws = null
      }
    }
  },
}
// eslint-disable-next-line no-unused-vars
function onRecords (_data) {
  // eslint-disable-next-line no-unused-vars
  let { startfreq, stepfreq, data } = JSON.parse(_data)
  let trace = String(data).split(',')
  let freqPoint = []
  let pointCount = trace.length
  for (let i = 0; i < pointCount; i++) {
    // trace[i] = parseFloat(trace[i])
    // freqPoint.push((startfreq + i * stepfreq) / 1000000)
    // trace[i] = parseFloat(trace[i]);
    let traceY = parseFloat(trace[i]) / 10;
    trace[i] = traceY;
    // freqPoint.push((startfreq + i * stepfreq) / 1000000)
    let traceX = (parseInt(startfreq) + i * parseInt(stepfreq)) / 1000000
    freqPoint.push(traceX)
  }
  return [freqPoint, trace]
}

function onRecordsDeli (_data) {
  // eslint-disable-next-line no-unused-vars
  let { measure_dt, traces, remarks } = _data
  console.log('remarks Deli ->', JSON.stringify(remarks))
  // eslint-disable-next-line no-unused-vars
  let { frequency, span, unit, ref, mr } = remarks
  let startFreq = frequency - span / 2
  let trace = traces[0].trace
  let pointCount = trace.length

  let step = span / pointCount
  console.log(`step ${step}`)
  let freqPoint = []
  for (let i = 0; i < pointCount; i++) {
    freqPoint.push(parseInt((startFreq + i * step) / 1000000))
  }
  return [freqPoint, trace, remarks]
}

function onRecordsJosh (_data) {
  // eslint-disable-next-line no-unused-vars
  let { measure_dt, traces, remarks } = _data
  console.log(JSON.stringify(remarks))
  // eslint-disable-next-line no-unused-vars
  let { frequency, span, unit, ref, mr } = remarks
  let startFreq = frequency - span / 2
  let trace = traces[0].trace
  let pointCount = trace.length

  let step = span / pointCount
  console.log(`step ${step}`)
  let freqPoint = []
  for (let i = 0; i < pointCount; i++) {
    freqPoint.push(parseInt((startFreq + i * step) / 1000000))
  }
  return [freqPoint, trace, remarks]
}

function onRecordsBoer (_data) {
  let { startFreq, stepFreq, data } = _data
  let freqPoint = []
  let traceMax = []
  let traceAvg = []
  let traceNoiseAvg = []
  let pointCount = data.length
  for (let i = 0; i < pointCount; i++) {
    freqPoint.push(parseInt((parseInt(startFreq) + i * parseInt(stepFreq)) / 1000000))
    let { avg, max, noiseAvg, occupancy } = data[i]
    traceMax.push(parseFloat(max).toFixed(2))
    traceAvg.push(parseFloat(avg).toFixed(2))
    traceNoiseAvg.push(parseFloat(noiseAvg).toFixed(2))
  }
  return [freqPoint, traceMax, traceAvg, traceNoiseAvg]
}

function onSpecRecords (_data) {
  let { frequencyStart, frequencyStep, channelCount, data } = _data
  let freqPoint = []
  let traceData = []
  let dataList = data.split(',')
  let pointCount = dataList.length
  for (let i = 0; i < pointCount; i++) {
    freqPoint.push(parseInt((parseInt(frequencyStart) + i * parseInt(frequencyStep)) / 1000000))
    let pointVal = dataList[i]
    traceData.push(parseFloat(pointVal).toFixed(2))
  }
  return [freqPoint, traceData]
}
</script>

<style scoped>
.search-conditions {
  margin-top: 3rem;
}

.right-condition {
  margin-top: 4rem;
}

.requestFormTitle {
  font-size: 20px;
  color: #000000;
  margin: 0 0 0 30px;
}
</style>
